先補上昨天未完成的改善。
RotationPanel的邊界最遠在半徑75以內,處理邏輯為邊界超過的時候,取同一個角度且距離原點距離為半徑的座標。
Circle()
.fill(Color.blue)
.frame(width: 20, height: 20)
.offset(rotationOffset)
.gesture(
DragGesture()
.onChanged { value in
let radius = 75.0 // 圓形的半徑
var newX = value.translation.width + lastOffset.width
var newY = value.translation.height + lastOffset.height
let distance = sqrt(newX * newX + newY * newY)
if distance > radius {
let angle = Double(atan2(newY, newX))
newX = radius * cos(angle)
newY = radius * sin(angle)
}
rotationOffset = CGSize(width: newX, height: newY)
}
.onEnded { _ in
lastOffset = rotationOffset
}
)
接下來我們看看哪邊可以重構,增加可讀性與易維護性。
@State private var circleSize: CGFloat = 20
@State private var brightness: Double = 1.0
@State private var circleColor: Color = .white
@State private var offset: CGSize = .zero
@State private var rotationOffset: CGSize = .zero